#!/bin/bash

DAEMON="splash-image"
DEFAULT="/usr/share/batocera/splash/logo-version-"$(cat /sys/class/graphics/fb0/virtual_size | sed 's/,/x/g')".png"
SPLASH_DIR=/userdata/splash

FM_IMAGE=".*\.\(jpg\|jpeg\|png\)"

do_filerandomize ()
{
    local array
    [[ -d "$SPLASH_DIR" ]] || return 1
    readarray -t array < <(find "$SPLASH_DIR" -maxdepth 1 -iregex "$1" -type f)
    if [[ ${#array[@]} -gt 0 ]]; then
        echo "${array[$RANDOM % ${#array[@]}]}"
    fi
}

do_start ()
{
    if ! test -e "$DEFAULT"
    then
        DEFAULT="/usr/share/batocera/splash/logo-version.png"
    fi

    image_file=$(do_filerandomize "$FM_IMAGE")

    if [[ -n "$image_file" ]]; then
        do_imagestart "$image_file"
    else
        do_imagestart "$DEFAULT"
    fi
}

do_imagestart ()
{
    image="$1"
    printf 'Image: %s: ' "$image"
    if test -e /dev/fb0
    then
        start-stop-daemon -S -b -q -m -p /var/run/user-splash-image.pid --exec /usr/bin/fbv -- -f -i "$image"
    fi
}

case "$1" in
    start)
        printf 'Starting %s: ' "$DAEMON"
        if grep -qE '^[ ]*splash.screen.enabled[ ]*=[ ]*1[ ]*$' "/boot/batocera-boot.conf"
        then
            do_start
            echo "OK"
	    else
	        echo "SKIPPED"
        fi
        ;;
    stop)
        start-stop-daemon -K -q -p /var/run/user-splash.pid
        ;;
    restart|reload)
        ;;
    *)
esac

exit $?
